import json
from django.shortcuts import render
from django.http import JsonResponse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.views.decorators.clickjacking import xframe_options_exempt
from .models import Role


# 角色视图
# Create your views here.

@xframe_options_exempt
def index(request):
    return render(request, "role/index.html")


def role_list(request):
    result = {"status": 1, "msg": "数据获取失败！"}
    data = request.GET
    try:
        page = data.get("page", 1)
        limit = data.get("limit", 10)
        roles = Role.objects.filter(is_delete=0)
        search = data.get("search")
        if search and search != "":
            roles = roles.filter(name__icontains=search)
        role_count = roles.count()
        paginator = Paginator(roles.order_by("-create_time"), limit)  # 每页多少条数据
        try:
            roles = paginator.page(page)  # 返回 page（页数）的数据
        except PageNotAnInteger:
            roles = paginator.page(1)  # 第一页
        except EmptyPage:
            roles = paginator.page(paginator.num_pages)  # 最后一页

        data_list = []
        for i in range(len(roles)):
            # 权限名称
            # pers_name = ""
            # for per in roles[i].permission.order_by("-create_time").all():
            #     if len(pers_name) == 0:
            #         pers_name += per.name
            #     else:
            #         pers_name += f" | {per.name}"
            data_list.append({
                "No": i + 1,
                "id": roles[i].id,
                "name": roles[i].name,
                # "pers": pers_name,
                "status": roles[i].status,
                "remark": roles[i].remark,
                "create_time": str(roles[i].create_time).split(".")[0],
            })

        result["data"] = data_list
        result["data_count"] = role_count
        result["status"] = 0
        result["msg"] = "数据获取成功！"
    except Exception as e:
        print(e)
    return JsonResponse(result)


@xframe_options_exempt
def role_add(request):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            print(data)
            name = data.get("name")
            remark = data.get("remark")
            # pers = data.get("pers")
            # if not isinstance(pers, list):
            #     result["msg"] = "权限递交方式错误！"
            #     return JsonResponse(result)
            role_name_exist = Role.objects.filter(name=name, is_delete=0).first()
            if role_name_exist:
                result["msg"] = "该角色名称已存在！"
                return JsonResponse(result)
            # per_exist = Permission.objects.filter(id__in=[int(i) for i in pers], status=1, is_delete=0).count()
            # if len(pers) != per_exist:
            #     result["msg"] = "存在不可用权限！"
            #     return JsonResponse(result)
            new_role = Role.objects.create(name=name, remark=remark)
            # new_role.permission.add(*[int(i) for i in pers])
            new_role.save()
            result["status"] = 1
            result["msg"] = "新增角色成功！"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        # pers = Permission.objects.filter(is_delete=0).order_by("-create_time").all()
        # return render(request, "role/add.html", {"pers": pers})
        return render(request, "role/add.html")


@xframe_options_exempt
def role_edit(request, role_id):
    if request.method == "POST":
        result = {"status": 0, "msg": "操作失败！"}
        data = json.loads(request.body)
        try:
            print(data)
            name = data.get("name")
            # pers = data.get("pers")
            remark = data.get("remark")
            role = Role.objects.filter(id=int(role_id), is_delete=0).first()
            if not role:
                result["msg"] = "请确认该角色是否存在！"
                return JsonResponse(result)
            # 判断权限是否可用
            # per_exist = Permission.objects.filter(id__in=[int(i) for i in pers], status=1, is_delete=0).count()
            # if len(pers) != per_exist:
            #     result["msg"] = "存在不可用权限！"
            #     return JsonResponse(result)
            if role.name != name:
                # 判断名称是否已存在
                role_name_exist = Role.objects.filter(~Q(id=int(role_id)), name=name, is_delete=0).first()
                if role_name_exist:
                    result["msg"] = "该角色名称已存在！"
                    return JsonResponse(result)
                role.name = name
            if role.remark != remark:
                role.remark = remark
            # 更新角色与权限的关系
            # role.permission.clear()
            # role.permission.add(*[int(i) for i in pers])
            # role.save()
            result["status"] = 1
            result["msg"] = "角色信息更改成功！"
        except Exception as e:
            print(e)
        return JsonResponse(result)
    else:
        role = Role.objects.filter(id=int(role_id), is_delete=0).first()
        # pers = Permission.objects.filter(is_delete=0).order_by("-create_time").all()
        # return render(request, "role/edit.html", {"role": role, "pers": pers, "pitch_on_per": [i.id for i in role.permission.all()]})
        return render(request, "role/edit.html", {"role": role})


def role_del(request, role_id):
    result = {"status": 0, "msg": "操作失败！"}
    if request.method == "DELETE":
        try:
            role = Role.objects.filter(id=int(role_id), is_delete=0).first()
            if role:
                role.is_delete = 1
                role.save()
                result["status"] = 1
                result["msg"] = "角色删除成功！"
            else:
                result["msg"] = "请确认该角色是否存在"
        except Exception as e:
            print(e)
    return JsonResponse(result)


def role_status(request, role_id):
    result = {"status": 0, "msg": "操作失败！"}
    if request.method == "POST":
        data = json.loads(request.body)
        try:
            status = data.get("status", None)
            if status is None or not isinstance(status, bool):
                result["msg"] = "请确认操作类型!"
                return JsonResponse(result)
            role = Role.objects.filter(id=int(role_id), is_delete=0).first()
            if role:
                if status is True and role.status == 0:
                    role.status = 1
                if status is False and role.status == 1:
                    role.status = 0
                role.save()
                result["status"] = 1
                result["msg"] = "角色启用成功!" if status is True else "角色禁用成功！"
            else:
                result["msg"] = "请确认角色是否正确!"
        except Exception as e:
            print(e)
    return JsonResponse(result)


